package com.atguigu.day07;

import com.atguigu.utils.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

public class Example5 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<UserBehavior> stream = env
                .readTextFile("/home/zuoyuan/flinktutorial0819/src/main/resources/UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] arr = value.split(",");
                        return new UserBehavior(
                                arr[0], arr[1], arr[2], arr[3],
                                Long.parseLong(arr[4]) * 1000L
                        );
                    }
                })
                .filter(r -> r.type.equals("pv"))
                .assignTimestampsAndWatermarks(WatermarkStrategy.<UserBehavior>forMonotonousTimestamps()
                        .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                            @Override
                            public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                return element.ts;
                            }
                        }));

        // 创建动态表执行环境
        EnvironmentSettings settings = EnvironmentSettings.newInstance().inStreamingMode().build();
        StreamTableEnvironment streamTableEnvironment = StreamTableEnvironment.create(env, settings);

        // 将数据流转换成动态表
        Table table = streamTableEnvironment
                .fromDataStream(
                        stream,
                        $("userId"),
                        $("itemId"),
                        $("categoryId").as("cid"),
                        $("type"),
                        $("ts").rowtime() // .rowtime表示ts字段是事件时间
                );

        // +I表示将数据插入到动态表中
//        DataStream<Row> rowDataStream = streamTableEnvironment.toChangelogStream(table);
//        rowDataStream.print();

        // 将动态表注册为临时视图
        streamTableEnvironment.createTemporaryView("userbehavior", table);

        // .keyBy.window.aggregate(增量聚合函数，全窗口聚合函数)
//        Table itemViewCountPerWindowBySQL = streamTableEnvironment
//                .sqlQuery("SELECT itemId, COUNT(itemId) as cnt, " +
//                        "HOP_START(ts, INTERVAL '5' MINUTES, INTERVAL '1' HOURS) as windowStart, " +
//                        "HOP_END(ts, INTERVAL '5' MINUTES, INTERVAL '1' HOURS) as windowEnd " +
//                        "FROM userbehavior GROUP BY itemId, HOP(ts, INTERVAL '5' MINUTES, INTERVAL '1' HOURS)");
//
//        streamTableEnvironment.toChangelogStream(itemViewCountPerWindowBySQL).print();

        // 实时热门商品
        // HOP(使用的时间戳，滑动距离，窗口长度)
        String innerSQL = "SELECT itemId, COUNT(itemId) as cnt, " +
                "HOP_START(ts, INTERVAL '5' MINUTES, INTERVAL '1' HOURS) as windowStart, " +
                "HOP_END(ts, INTERVAL '5' MINUTES, INTERVAL '1' HOURS) as windowEnd " +
                "FROM userbehavior GROUP BY itemId, HOP(ts, INTERVAL '5' MINUTES, INTERVAL '1' HOURS)";

        String outerSQL = "SELECT * FROM (" + "" +
                "SELECT *, ROW_NUMBER() OVER (PARTITION BY windowEnd ORDER BY cnt DESC) as row_num FROM (" + innerSQL + ")" +
                "" + ") WHERE row_num <= 3";

        // -U：撤回数据
        // +U：更新数据
        Table result = streamTableEnvironment.sqlQuery(outerSQL);
        streamTableEnvironment.toChangelogStream(result).print();

        env.execute();
    }
}
